package com.ddone.base.handler;

import com.baomidou.mybatisplus.extension.api.R;
import com.ddone.common.exception.BusinessException;
import com.ddone.common.result.Response;
import com.ddone.common.result.ResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.List;

/**
 * @author ddone
 * @date 2024/4/11-15:58
 */
@Slf4j
@Component
//Spring容器自动管理
@RestControllerAdvice
//在controller层添加通知。如果使用@ControllerAdvice，则方法上需要添加@ResponseBody
public class UnifiedExceptionHandler {

    /**
     * 未定义异常
     */
    @ExceptionHandler(value = Exception.class) //当controller中抛出Exception，则捕获
    public Response<Object> handleGlobalException(Exception e) {
        log.error(e.getMessage(), e);
        log.error("出现异常: " + ExceptionUtils.getStackTrace(e));
        return Response.fail().message(e.getMessage());
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(BusinessException.class)
    public Response<Object> handleBusinessException(BusinessException e) {
        log.error(e.getMessage(), e);
        log.error("出现异常: " + ExceptionUtils.getStackTrace(e));
        return Response.fail().message(e.getMessage()).code(e.getCode());
    }


    @ExceptionHandler({
            NoHandlerFoundException.class,
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            // MethodArgumentNotValidException.class,
            HttpMediaTypeNotAcceptableException.class,
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class,
            MissingServletRequestPartException.class,
            AsyncRequestTimeoutException.class
    })
    public Response<Object> handleServletException(Exception e) {
        log.error(e.getMessage(), e);
        //SERVLET_ERROR(-102, "servlet请求异常"),
        return Response.fail().message(e.getMessage()).code(ResponseEnum.SERVLET_ERROR.getCode());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<Object> handArgException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        return Response.fail().message(allErrors.get(0).getDefaultMessage()).code(ResponseEnum.ARGS_IS_NOT_VALID.getCode());
    }

}
